/** @format */
const jwt = require('jsonwebtoken')
const { Base64 } = require('js-base64')
import { BaseDao } from '../../sdk'
import { JWT_DB } from '../../db'
import dayjs = require('dayjs')
import { APP_KEY } from '../../constants'

function getKey(param, key) {
  return Base64.encode(`${key}-${param}-${key}`)
}

function jwt_sign(param, key) {
  const token = jwt.sign({ sign: param }, getKey(param, key), { expiresIn: 3600 })
  return `Bearer ${token}`
}

export async function sendWildWoodRequest(context, urlObj: IRequestObject, param: string, body) {
  const jwtdao: IBaseDao = new BaseDao(context, JWT_DB)
  const jwtInfo: any = await jwtdao.findOne({ name: 'jwt' })
  const { httpKey } = jwtInfo
  if (body) {
    body.timestamp = dayjs().format()
    body.appkey = APP_KEY
  }
  if (body?.properties) {
    body.properties.timestamp = dayjs().format()
    body.properties.appkey = APP_KEY
  }

  const requestObj = {
    domain: urlObj.domain,
    path: urlObj.path,
    params: '',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      Authorization: jwt_sign(param, httpKey),
      appkey: APP_KEY,
      timestamp: dayjs().format(),
      'Auth-Id': param,
      'X-B3-TraceId': context.data.traceId
    },
    body
  }
  try {
    const result = await context.cloud.httpApi.invoke(requestObj)
    return JSON.parse(result)
  } catch (error) {
    console.log('调用wildwood接口失败', error)
    return false
  }
}
